<template>
    <div :class="props.class">
        <div :class="props.pagination ? `table-wrapper-with-pagination` : `table-wrapper`">
            <el-table ref="tableRef" :data="props.data.rows" :stripe="true" :border="true" style="width: 100%;"
                @row-click="handleOnRowClick" @row-contextmenu="handleOnRowRightClick"
                @row-dblclick="handleOnRowDoubleClick" @sort-change="handleSortChange" height="100%">
                <el-table-column type="selection" fixed="left" />
                <el-table-column fixed="left" :label="lang.OPERATION"
                    :width="(props.buttonList.filter(button => button.menuPositionCode === `MenuPosition_Row`).length - 1) * 50 + 60"
                    v-if="props.buttonList && props.buttonList.filter(button => button.menuPositionCode === `MenuPosition_Row`).length > 0">
                    <template #default="scope">
                        <el-popover
                            v-for="button in props.buttonList.filter(button => button.menuPositionCode === `MenuPosition_Row`)"
                            effect="light" trigger="hover" placement="top" width="auto">
                            <template #default>
                                <span>{{ button.name }}</span>
                            </template>
                            <template #reference>
                                <el-button size="small" circle @click.prevent="handleOnButtonClick(button, scope.row)">
                                    <el-image class="icon-button" :src="`/image/${button.icon}`" fit="fill" alt="" />
                                </el-button>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>

                <template v-for="column in props.columnList.filter(column => !column.isHidden)">
                    <el-table-column :width="column.width" v-if="column.controlTypeCode === `ControlType_Boolean`"
                        :prop="column.prop" :label="column.label" :sortable="props.sortable ? `custom` : false">
                        <template #default="scope">
                            <el-tag v-if="scope.row[column.prop] === `1`" type="success">{{ lang.YES }}</el-tag>
                            <el-tag v-else type="danger">{{ lang.NO }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :width="column.width" v-else-if="column.controlTypeCode === `ControlType_Select`"
                        :prop="column.prop" :label="column.label" :sortable="props.sortable ? `custom` : false">
                        <template #default="scope">
                            {{ getSelectValue(scope.row, column) }}
                        </template>
                    </el-table-column>
                    <el-table-column :width="column.width"
                        v-else-if="column.controlTypeCode === `ControlType_MultiSelect`" :prop="column.prop"
                        :label="column.label" :sortable="props.sortable ? `custom` : false">
                        <template #default="scope">
                            {{ getMultiSelectValue(scope.row, column) }}
                        </template>
                    </el-table-column>
                    <el-table-column :width="column.width" v-else :prop="column.prop" :label="column.label"
                        :sortable="props.sortable ? `custom` : false" />
                </template>
            </el-table>
        </div>
        <div class="pagination-wrapper" v-if="props.pagination">
            <el-pagination v-model:currentPage="states.pagination.pageNumber" @size-change="handlePageSizeChange"
                @current-change="handlePageNumberChange" v-model:page-size="states.pagination.pageSize"
                :page-sizes="[20, 50, 100]" background layout="sizes, prev, pager, next, total"
                :total="props.data.total" />
        </div>
    </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { lang } from "../lang";

const tableRef = ref();
const props = defineProps([
    "class",
    "columnList",
    "buttonList",
    "onButtonClick",
    "dictionary",
    "data",
    "onRefresh",
    "pagination",
    "sortable"
]);

const states = reactive({
    pagination: {
        pageSize: 20,
        pageNumber: 1
    },
    sorter: {
        sortField: "",
        sortOrder: "",
    }
});

const handleOnButtonClick = (button, row) => {
    tableRef.value.clearSelection();
    tableRef.value.toggleRowSelection(row, true);
    props.onButtonClick(button);
};

const handleOnRowClick = (row, column, event) => {
};

const handleOnRowDoubleClick = (row, column, event) => {

};

const handleOnRowRightClick = (row, column, event) => {
    tableRef.value.clearSelection();
    tableRef.value.toggleRowSelection(row, true);
};

const handleSortChange = ({ column, prop, order }) => {
    states.sorter.sortField = prop;
    states.sorter.sortOrder = order;
    refresh();
};

const handlePageSizeChange = () => {
    refresh();
};

const handlePageNumberChange = () => {
    refresh();
};

const refresh = () => {
    props.onRefresh();
};

const getSelectValue = (row, column) => {
    let result = row[column.prop];
    if (props.dictionary && props.dictionary[column.prop]) {
        let index = props.dictionary[column.prop].findIndex(item => item.id === result);
        if (index >= 0) {
            result = props.dictionary[column.prop][index].text;
        }
    }

    return result;
};

const getMultiSelectValue = (row, column) => {
    let result = row[column.prop];
    if (props.dictionary && props.dictionary[column.prop]) {
        let valueList = result.split(",");
        let resultList = [];
        valueList.forEach(value => {
            let index = props.dictionary[column.prop].findIndex(item => item.id === value);
            if (index >= 0) {
                resultList.push(props.dictionary[column.prop][index].text);
            } else {
                resultList.push(value);
            }
        });

        result = resultList.join();
    }

    return result;
};

const getSelectionRows = () => {
    return tableRef.value.getSelectionRows();
};

const getPagination = () => {
    return states.pagination;
};

const getSorter = () => {
    if (states.sorter.sortField && states.sorter.sortOrder)
        return states.sorter;
    else return null;
};

const initialize = () => {
    states.pagination = {
        pageNumber: 1,
        pageSize: 20,
    }
};

defineExpose({
    getSelectionRows,
    getPagination,
    getSorter,
    initialize,
});
</script>
<style scoped lang="less">
.icon-button {
    width: 18px;
    height: 18px;
}

.table-wrapper {
    width: 100%;
    height: calc(100% - 10px);
}

.table-wrapper-with-pagination {
    width: 100%;
    height: calc(100% - 64px);
}

.pagination-wrapper {
    width: 100%;
    height: 64px;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>